//
//  LHSelectPhotoManager.m
//  Loohoo
//
//  Created by 陈镇 on 2025/4/21.
//

#import "LHSelectPhotoManager.h"
#import "SLUserPermissionsManager.h"
#import "UIImage+LHAdd.h"
@interface LHSelectPhotoManager ()<QMUIAlbumViewControllerDelegate,QMUIImagePickerViewControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,copy) LHSelectPhotoManagerBlock block;



@end


static LHSelectPhotoManager *_manager = nil;


@interface LHSelectPhotoManager ()

@property(nonatomic,assign) NSInteger maxCount;
//是不是单选
@property(nonatomic,assign) NSInteger isSing;



@end
@implementation LHSelectPhotoManager


+(instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[LHSelectPhotoManager alloc] init];
    });
    return _manager;
}

+(void)createManagerBlock:(LHSelectPhotoManagerBlock)block{
    [LHSelectPhotoManager sharedManager].isSing = YES;
    [LHSelectPhotoManager createManagerCount:1 block:block];
    
  
}

+(void)createManagerCount:(NSInteger)count block:(LHSelectPhotoManagerBlock)block{
    [LHSelectPhotoManager sharedManager].isSing = NO;
    LHSelectPhotoManager *manager = [LHSelectPhotoManager sharedManager];
    manager.maxCount = count;
    manager.block = block;
    [manager showAlert];
    
    
}

+(void)openPhotoCount:(NSInteger)count block:(LHSelectPhotoManagerBlock)block{
 
    [LHSelectPhotoManager sharedManager].isSing = NO;
    LHSelectPhotoManager *manager = [LHSelectPhotoManager sharedManager];
    manager.maxCount = count;
    manager.block = block;
    [manager openPhoto];

}

+(void)openCamerBlock:(LHSelectPhotoManagerBlock)block{
    [LHSelectPhotoManager sharedManager].isSing = YES;
    LHSelectPhotoManager *manager = [LHSelectPhotoManager sharedManager];
    manager.maxCount = 1;
    manager.block = block;
    [manager openCamer];
    

}
-(void)showAlert{
    __weak typeof(self) weakSelf = self;
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    
    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SLUserPermissionsManager isHaveCameraPermissionsBlock:^(BOOL isCan) {
            if (isCan) {
                [weakSelf openCamer];
            }
        }];

    }];
    
    
    UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [SLUserPermissionsManager isHavePhotoPermissionsBlock:^(BOOL isCan) {
            if (isCan) {
                [weakSelf openPhoto];
            }
        }];
    }];
    UIAlertAction *act3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [vc addAction:act1];
    [vc addAction:act2];
    [vc addAction:act3];
    
    [CurrentVC presentViewController:vc animated:YES completion:0];
}


-(void)openFirstPhoto{

    
    [[QMUIAssetsManager sharedInstance] enumerateAllAlbumsWithAlbumContentType:QMUIAlbumContentTypeOnlyPhoto usingBlock:^(QMUIAssetsGroup *resultAssetsGroup) {
            
        if (resultAssetsGroup) {

            if (resultAssetsGroup.phAssetCollection.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary) {
                QMUIImagePickerViewController *imagePickerViewController = [[QMUIImagePickerViewController alloc] init];
                imagePickerViewController.imagePickerViewControllerDelegate = self;
                imagePickerViewController.maximumSelectImageCount = self.maxCount;
                imagePickerViewController.allowsMultipleSelection = YES;
                [imagePickerViewController.sendButton setTitle:@"选择" forState:UIControlStateNormal];
                imagePickerViewController.minimumImageWidth = 90;
                if (self.isSing) {
                    imagePickerViewController.allowsMultipleSelection = NO;
                }
                [imagePickerViewController refreshWithAssetsGroup:resultAssetsGroup];
                
                [CurrentVC.navigationController pushViewController:imagePickerViewController animated:NO];
                
                return;
            }

        }
        
    }];
    

    
}
-(void)openCamer{
    [SLUserPermissionsManager isHaveCameraPermissionsBlock:^(BOOL isCan) {
        if (isCan) {
            UIImagePickerController *imagePickerVc = [UIImagePickerController new];
            imagePickerVc.delegate = self;
            
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
                imagePickerVc.sourceType = sourceType;
                imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
                [CurrentVC presentViewController: imagePickerVc animated:YES completion:nil];
            } else {
                RTLog(@"模拟器中无法打开照相机,请在真机中使用");
            }
        }
    }];

}

-(void)openPhoto{
    
    [SLUserPermissionsManager isHavePhotoPermissionsBlock:^(BOOL isCan) {
        if (isCan) {
            // 创建一个 QMUIAlbumViewController 实例用于呈现相簿列表
            QMUIAlbumViewController *albumViewController = [[QMUIAlbumViewController alloc] init];
            albumViewController.albumViewControllerDelegate = self;
            albumViewController.contentType = QMUIAlbumContentTypeOnlyPhoto;
            albumViewController.title = @"选择图片";
        //    albumViewController.view.tag = 1048;
            QMUINavigationController *navigationController = [[QMUINavigationController alloc] initWithRootViewController:albumViewController];
            navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
            // 获取最近发送图片时使用过的相簿，如果有则直接进入该相簿
            [albumViewController pickLastAlbumGroupDirectlyIfCan];
            
            [CurrentVC presentViewController:navigationController animated:YES completion:NULL];
        }
    }];

}
#pragma mark - <QMUIAlbumViewControllerDelegate>

- (QMUIImagePickerViewController *)imagePickerViewControllerForAlbumViewController:(QMUIAlbumViewController *)albumViewController {
    QMUIImagePickerViewController *imagePickerViewController = [[QMUIImagePickerViewController alloc] init];
    imagePickerViewController.imagePickerViewControllerDelegate = self;
    imagePickerViewController.maximumSelectImageCount = self.maxCount;
    imagePickerViewController.view.tag = albumViewController.view.tag;
    imagePickerViewController.allowsMultipleSelection = YES;
    [imagePickerViewController.sendButton setTitle:@"选择" forState:UIControlStateNormal];
    imagePickerViewController.minimumImageWidth = 90;
    if (self.isSing) {
        imagePickerViewController.allowsMultipleSelection = NO;
    }

    return imagePickerViewController;
}
- (void)imagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController didSelectImageWithImagesAsset:(QMUIAsset *)imageAsset afterImagePickerPreviewViewControllerUpdate:(QMUIImagePickerPreviewViewController *)imagePickerPreviewViewController{
    
    if (self.isSing) {
        [imagePickerViewController dismissViewControllerAnimated:YES completion:0];
        
        // 储存最近选择了图片的相册，方便下次直接进入该相册
        [QMUIImagePickerHelper updateLastestAlbumWithAssetsGroup:imagePickerViewController.assetsGroup ablumContentType:QMUIAlbumContentTypeOnlyPhoto userIdentify:nil];
        
        
        if (self.block) {
            self.block(@[[imageAsset originImage]]);
        }
    }

    
//    RTLog(@"%@",[imageAsset originImage]);
}

- (void)imagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController didFinishPickingImageWithImagesAssetArray:(NSMutableArray<QMUIAsset *> *)imagesAssetArray{
    [imagePickerViewController dismissViewControllerAnimated:YES completion:0];
    // 储存最近选择了图片的相册，方便下次直接进入该相册
    [QMUIImagePickerHelper updateLastestAlbumWithAssetsGroup:imagePickerViewController.assetsGroup ablumContentType:QMUIAlbumContentTypeOnlyPhoto userIdentify:nil];
    
    
    NSMutableArray *tmp = [NSMutableArray array];
    for (QMUIAsset *imageAsset in imagesAssetArray) {
        if ([imageAsset originImage]) {
            [tmp addObject:[imageAsset originImage]];
        }

    }
    if (self.block) {
        self.block(tmp);
    }
    
}


-(QMUIImagePickerPreviewViewController *)imagePickerPreviewViewControllerForImagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController{
    
    
    QMUIImagePickerPreviewViewController *vc = [[QMUIImagePickerPreviewViewController alloc] init];
    
    vc.imagesAssetArray = imagePickerViewController.imagesAssetArray;
    vc.selectedImageAssetArray = imagePickerViewController.imagesAssetArray;
    return vc;
    
}
#pragma mark -- 相机代理
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
        if (self.block) {
            self.block(@[image]);
        }
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
@end



@implementation LHSelectPhotoManager (uploadImage)


//
//+(void)uploadImage:(UIImage *)image dic:(NSString *)dic block:(LHSelectPhotoUploadBlock)block{
//    
//    UIImage * tmp = [image compressImageQuality:CGSizeMake(400, 400) toByte:1024*100];
// 
//    
//    SLUploadImageRequest *req = [[SLUploadImageRequest alloc] initWithImage:tmp andPathNameType:ThePathNameType_Common directory:dic];
//    [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//   
//        NSDictionary *dataDic = request.responseJSONObject[@"data"];
//        NSString *url = dataDic[@"url"];
//        
//        if (block && url.length > 0) {
//            block(@[url]);
//        }
//        
//    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//         
//        if (block ) {
//            block(@[]);
//        }
//    }];
//}

@end
